//
//  Modal.swift
//  d11
//
//  Created by Wai Yin Chan on 3/10/2017.
//  Copyright © 2017 Tech_001. All rights reserved.
//

import Foundation
import UIKit

protocol Modal {
    func show(target: UIViewController, animated:Bool)
    func dismiss(animated:Bool)
    var backgroundView:UIView {get}
    var dialogView:UIView {get set}
}

extension Modal where Self:UIView{
    func show(target: UIViewController, animated:Bool){
        self.backgroundView.alpha = 0
        //self.dialogView.center = CGPoint(x: self.center.x, y: self.frame.height + self.dialogView.frame.height/2)
        self.dialogView.center  = self.center
        self.dialogView.transform = CGAffineTransform(scaleX: 0.25, y: 0.25)
        
        //UIApplication.shared.delegate?.window??.rootViewController?.view.addSubview(self)
     //   target.parent?.view.addSubview(self)
        let window: UIWindow  = ((UIApplication.shared.delegate?.window)!)!
        window.addSubview(self)
        if animated {
            UIView.animate(withDuration: 0.25, animations: {
                self.backgroundView.alpha = 0.6
            })
            UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 20, options: UIView.AnimationOptions(rawValue: 0), animations: {
                self.dialogView.center  = self.center
                self.dialogView.transform = CGAffineTransform(scaleX: 1, y: 1)
            }, completion: { (completed) in
                
            })
        }else{
            self.backgroundView.alpha = 0.66
            self.dialogView.center  = self.center
        }
    }
    
    func dismiss(animated:Bool){
        if animated {
            UIView.animate(withDuration: 0.25, animations: {
                self.backgroundView.alpha = 0
            }, completion: { (completed) in
                
            })
            UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 10, options: UIView.AnimationOptions(rawValue: 0), animations: {
                //self.dialogView.center = CGPoint(x: self.center.x, y: self.frame.height + self.dialogView.frame.height/2)
                self.dialogView.alpha = 0
                self.dialogView.transform = CGAffineTransform(scaleX: 0.25, y: 0.25)
            }, completion: { (completed) in
                self.removeFromSuperview()
            })
        }else{
            self.removeFromSuperview()
        }
        
    }
}
